package com.itheima.sh.web;

import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author stay foolish
 * @description 行至水穷处, 坐看云起时
 * @date 2022/11/15 19:43:29
 * @description TODD
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.处理请求乱码
        request.setCharacterEncoding("utf-8");
        // 2.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        // 3.创建User对象
        User user = new User();
        // 4.将请求参数封装到对象中
        user.setUsername(username);
        user.setPassword(password);
        // 5.创建service业务层对象
        UserServiceImpl userService = new UserServiceImpl();
        // 6.使用业务层对象调用业务层的登录方法将User对象传递到业务层
        User u = userService.login(user);
        // 7.判断返回值u是否等于null
        if (u == null) {
            // 7.1如果等于null,说明用户名或者密码错误,响应给前端false
            response.getWriter().write("false");
        } else {
            // 7.2如果不等于null,说明登录成功,响应给前端true
            response.getWriter().write("true");
        }
    }
}

